import { makeAutoObservable, runInAction } from 'mobx'

class AuthStore {
  user: User | null = null
  isAuthenticated = false
  loading = false
  error: string | null = null

  constructor() {
    makeAutoObservable(this)
    this.loadUserFromStorage()
  }

  async loadUserFromStorage() {
    this.loading = true
    try {
      const userJson = localStorage.getItem('user')
      if (userJson) {
        const user = JSON.parse(userJson) as User
        runInAction(() => {
          this.user = user
          this.isAuthenticated = true
        })
      }
    } catch (err) {
      console.error('加载用户缓存失败！', err)
    } finally {
      runInAction(() => {
        this.loading = false
      })
    }
  }

  async register(username: string, password: string): Promise<void> {
    this.loading = true
    this.error = null
    try {
      // 模拟API调用
      await new Promise((resolve) => setTimeout(resolve, 500))

      const user: User = {
        id: Date.now().toString(),
        username,
        password
      }

      localStorage.setItem('user', JSON.stringify(user))

      runInAction(() => {
        this.user = user
        this.isAuthenticated = true
      })
    } catch (err) {
      runInAction(() => {
        this.error = 'Registration failed'
      })
    } finally {
      runInAction(() => {
        this.loading = false
      })
    }
  }

  async login(username: string, password: string): Promise<void> {
    this.loading = true
    this.error = null
    try {
      await new Promise((resolve) => setTimeout(resolve, 500))

      const user: User = {
        id: Date.now().toString(),
        username,
        password
      }

      localStorage.setItem('user', JSON.stringify(user))
      // 确保状态更新的原子性 自动追踪依赖
      runInAction(() => {
        this.user = user
        this.isAuthenticated = true
      })
    } catch (err) {
      runInAction(() => {
        this.error = '登录失败'
      })
    } finally {
      runInAction(() => {
        this.loading = false
      })
    }
  }

  logout(): void {
    localStorage.removeItem('user')
    runInAction(() => {
      this.user = null
      this.isAuthenticated = false
    })
  }

  updateUsername(newUsername: string): void {
    if (this.user) {
      const updatedUser: User = {
        ...this.user,
        username: newUsername
      }
      localStorage.setItem('user', JSON.stringify(updatedUser))

      runInAction(() => {
        this.user = updatedUser
      })
    }
  }
}

export const authStore = new AuthStore()
